import { CloseOutlined, PlusOutlined } from "@ant-design/icons";
import { Row, Col, Input, Button } from "antd";
import { GFS } from "@/hooks/useAssignGlobalProps";
import { useEffect, useMemo, useState } from "react";
import { FormulaEditor } from "./FormulaEditor";
import { isEmpty } from "lodash-es";
interface KeyValueSetterProps {
  id?: string;
  value?: Record<string, any>;
  onChange?: (value: Record<string, any>|undefined) => void;
}

export function KeyValueSetter({ id, value, onChange }: KeyValueSetterProps) {
  const [items, setItems] = useState<Record<string, any>[]>([]);
  const hasValue = useMemo(()=>{
    return items.length>0
  }, [items])
  
  useEffect(() => {
    initData(value);
  }, [value]);
  function initData(objData: Record<string, any> | undefined) {
    const arr = Object.entries(objData||{})
    const tableData = arr.map(cell => {
      const obj: Record<string, any> = {};
      obj.key = cell[0];
      obj.value = cell[1];
      return obj;
    })
    setItems(tableData);
  }

  const handleChange = (val: string, key: string, index: number, cell?: Record<string, any>) => {
    const newItems = items.map((item, mIndex) => {
      if (mIndex === index) {
        item[key] = val;
        return item;
      }
      return item;
    });
    setItems(newItems);
    updateValue(newItems);
  };
  function handleDelete(index: number) {
    const newItems = items.filter((_, mIndex) => mIndex !== index);
    setItems(newItems);
    updateValue(newItems);
  }

  function handleAdd() {
    const emptyKey = items.some(item => !item.key);
    if (!emptyKey) {
      const record = { key: "", label: "" };
      const newItems = [...items, record];
      setItems(newItems);
    } else {
      GFS.message.warning("只能新增一行！");
    }
  }
  function updateValue(arr: Record<string, any>[]) {
    const obj = arr.reduce((acc, cur, index) => {
      acc[cur.key] = cur.value;
      return acc;
    }, {} as Record<string, any>);
    onChange?.(isEmpty(obj) ? undefined : obj);
  }
  return (
    <section id={id}>
      {/* <Row gutter={8} className="mb-[2px] text-center font-medium">
        <Col span={12}> 键名 </Col>
        <Col span={8}> 值 </Col>
      </Row> */}
      {!hasValue && <div className="h-8 flex items-center text-gray-300">&lt;空&gt;</div>}
      {items.map((cell: Record<string, string>, cIndex) => {
        return (
          <Row key={cIndex} className="mb-2" wrap={false}>
            <Row gutter={8} key={cIndex}>
              <Col span={10}>
                <Input placeholder="参数名" value={cell.key} title={cell.key} onChange={e => handleChange(e.target.value, "key", cIndex)} />
              </Col>
              <Col span={14}>
                <FormulaEditor value={cell.value} onChange={val => handleChange(val, "value", cIndex)} />
              </Col>
            </Row>
            <CloseOutlined className="ml-2" onClick={() => handleDelete(cIndex)} style={{ color: "rgba(0,0,0,.45)" }} />
          </Row>
        );
      })}
      <Button onClick={handleAdd} icon={<PlusOutlined />} className="mb-2">
        添加
      </Button>
    </section>
  );
}
